package com.aiyige.page.publish.learnvideo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.location.LocationService;
import com.aiyige.location.model.LocationData;
import com.aiyige.model.Divide;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.selectpublishinterest.SelectPublishInterestPage;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.CommonTipDialog;
import com.aiyige.page.publish.guarantee.GuaranteePage;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.guarantee.util.GuaranteeUtil;
import com.aiyige.page.publish.inputintroduction.InputIntrodutionPage;
import com.aiyige.page.publish.inputtitle.SingleLineInputPage;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoFormModel;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoItem;
import com.aiyige.page.publish.selectprice.SelectPricePage;
import com.aiyige.page.publish.selectprice.model.PriceItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.TrackUtil;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.DivideUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeSpaceInputFilter;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.LocalMediaUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxNetTool;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Track("教学视频发布页")
@Route(path = ARouterConfig.PublishLearnVideoFormPage)
public class PublishLearnVideoFormPage extends BaseActivity {
    public static final String TAG = PublishLearnVideoFormPage.class.getSimpleName();
    public static final int REQUEST_CODE_INPUT_TITLE = 1;
    public static final int REQUEST_CODE_SELECT_COVER = 2;
    public static final int REQUEST_CODE_SELECT_PRICE = 3;
    public static final int REQUEST_CODE_SELECT_INTEREST = 4;
    public static final int REQUEST_CODE_INPUT_COURSE_INTRODUCTION = 10;
    public static final int REQUEST_CODE_SELECT_GUARANTEE = 11;
    public static final int REQUEST_CODE_EDIT_SPLIT_VIDEO = 12;

    public static final String EXTRA_KEY_FORM_MODEL = "com.aiyige.extra.EXTRA_KEY_FORM_MODEL";
    @BindView(R.id.containerLayout)
    View containterLayout;
    @BindView(R.id.finishLayout)
    View finishLayout;
    @BindView(R.id.coverIv)
    ImageView coverIv;
    @BindView(R.id.priceTv)
    TextView priceTv;
    @BindView(R.id.interestTv)
    TextView interestTv;
    @BindView(R.id.teacherEt)
    EditText teacherEt;
    @BindView(R.id.courseIntroductionTv)
    TextView courseIntroductionTv;
    @BindView(R.id.splitVideoTv)
    TextView splitVideoTv;
    @BindView(R.id.saveBtn)
    TextView saveBtn;
    @BindView(R.id.submitBtn)
    TextView submitBtn;
    @BindView(R.id.titleBarTitleTv)
    TextView titleBarTitleTv;
    @Autowired
    PublishLearnVideoFormModel formModel;


    BroadcastReceiver broadcastReceiver;
    LocationData locationData = new LocationData();
    @BindView(R.id.titleBackBtn)
    TextView titleBackBtn;
    @BindView(R.id.coverLayout)
    RelativeLayout coverLayout;
    @BindView(R.id.priceLayout)
    RelativeLayout priceLayout;
    @BindView(R.id.interestLayout)
    RelativeLayout interestLayout;
    @BindView(R.id.courseTypeLayout)
    RelativeLayout courseTypeLayout;
    @BindView(R.id.suitablePeopleLayout)
    RelativeLayout suitablePeopleLayout;
    @BindView(R.id.learnTargetLayout)
    RelativeLayout learnTargetLayout;
    @BindView(R.id.teacherLayout)
    RelativeLayout teacherLayout;
    @BindView(R.id.titleLayout)
    View titleLayout;
    @BindView(R.id.courseIntroductionLayout)
    RelativeLayout courseIntroductionLayout;
    @BindView(R.id.splitVideoLayout)
    RelativeLayout splitVideoLayout;
    TrackEvent trackEvent = new TrackEvent();
    String mediaSource = TrackUtil.MEDIA_SOURCE_DEFAULT;
    @BindView(R.id.platformDividendEt)
    EditText platformDividendEt;
    @BindView(R.id.platformDividendLayout)
    RelativeLayout platformDividendLayout;
    KeyboardUtil.KeyboardMonitor keyboardMonitor;
    @BindView(R.id.titleEt)
    EditText titleEt;
    @BindView(R.id.courseTypeEt)
    EditText courseTypeEt;
    @BindView(R.id.suitablePeopleEt)
    EditText suitablePeopleEt;
    @BindView(R.id.learnTargetEt)
    EditText learnTargetEt;
    Divide divide = null;
    Handler mainHandler;
    @BindView(R.id.guaranteeTv)
    TextView guaranteeTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_learn_video_form);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            ToastX.show(R.string.unknown_error);
            finish();
            return;
        }
        mainHandler = new Handler(Looper.getMainLooper());
        keyboardMonitor = KeyboardUtil.KeyboardMonitor.newBuilder()
                .container(containterLayout)
                .callback(new KeyboardUtil.KeyboardMonitor.Callback() {
                    @Override
                    public void onKeyboardShow() {
                        finishLayout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onKeyboardHide() {
                        finishLayout.setVisibility(View.VISIBLE);
                        containterLayout.requestFocus();
                    }
                })
                .build()
                .install();
        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
            titleBarTitleTv.setText(R.string.edit_learn_video);
            saveBtn.setVisibility(View.GONE);
        } else {
            titleBarTitleTv.setText(R.string.add_new_learn_video);
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case LocationService.ACTION_LOCATION_FINISH: {
                            locationData = LocationService.obtainLocationData(intent);
                            formModel.setLocationData(locationData);
                            break;
                        }
                        default:
                            break;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "onReceive:" + Log.getStackTraceString(e));
                }
            }
        };
        platformDividendEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (divide == null) {
                    platformDividendEt.setText(TextUtils.isEmpty(formModel.getPlatformDividend()) ? "" : formModel.getPlatformDividend());
                    return;
                }
                if (!hasFocus) {
                    try {
                        double dividend = Double.parseDouble(platformDividendEt.getText().toString().trim());
                        if (dividend / 100 < divide.getMin()) {
                            throw new Exception("");
                        }
                        if (dividend / 100 > divide.getMax()) {
                            throw new Exception("Max");
                        }
                        formModel.setPlatformDividend(StringUtils.platformDividendFormat(dividend));
                    } catch (Exception e) {
                        ToastX.show(StringUtils.getString(R.string.platform_dividend_range, StringUtils.platformDividendFormat(divide.getMin() * 100), StringUtils.platformDividendFormat(divide.getMax() * 100)));
                        if ((e != null && !TextUtils.isEmpty(e.getMessage())) && e.getMessage().equals("Max")) {
                            formModel.setPlatformDividend(StringUtils.platformDividendFormat(divide.getMax() * 100));
                        } else {
                            formModel.setPlatformDividend(StringUtils.platformDividendFormat(divide.getMin() * 100));
                        }
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            platformDividendEt.setSelection(platformDividendEt.getText().length());
                        }
                    });
                }
            }
        });
        titleEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(30, false)});
        titleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setTitle(s.toString());
            }
        });


        titleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());

        teacherEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        teacherEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setTeacher(s.toString());
            }
        });
        teacherEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());


        learnTargetEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        learnTargetEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setLearnTarget(s.toString());
            }
        });
        learnTargetEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());


        suitablePeopleEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        suitablePeopleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setSuitablePeople(s.toString());
            }
        });
        suitablePeopleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());

        courseTypeEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        courseTypeEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setCourseType(s.toString());
            }
        });
        courseTypeEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());


        registerReceiver(broadcastReceiver, intentFilter);
        LocationService.startLocation(this);
        updateView();
        new MaybeRequestDivide(this, formModel).execute();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }


    public boolean checkFormValidate() {
//        if (!locationData.isSuccess()) {
//            ToastX.show(R.string.location_unfinished);
//            LocationService.startLocation(this);
//            return false;
//        }

//        if (ListUtil.isEmpty(formModel.getSelectTagItemList())) {
//            ToastX.show(R.string.please_select_tag);
//            return false;
//        }
        boolean result = true;
        if (TextUtils.isEmpty(formModel.getPlatformDividend())) {
            result = false;
            platformDividendLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            platformDividendLayout.setBackgroundResource(R.color.white);
        }

        if (ListUtil.isEmpty(formModel.getInterestList())) {
            result = false;
            interestLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            interestLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getTitle())) {
            result = false;
            titleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            titleLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getCoverUrl())) {
            result = false;
            coverLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            coverLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getPrice())) {
            result = false;
            priceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            priceLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getCourseType())) {
            result = false;
            courseTypeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            courseTypeLayout.setBackgroundResource(R.color.white);
        }
//
//        if (TextUtils.isEmpty(formModel.getSelectSuitablePeopleItem().getTitle())) {
//            result = false;
//            suitablePeopleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//        } else {
//            suitablePeopleLayout.setBackgroundResource(R.color.white);
//        }

//        if (ListUtil.isEmpty(formModel.getSelectLearnTargetItemList())) {
//            result = false;
//            learnTargetLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//        } else {
//            learnTargetLayout.setBackgroundResource(R.color.white);
//        }

//        if (TextUtils.isEmpty(formModel.getTeacherItem().getTitle())) {
//            result = false;
//            teacherLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//        } else {
//            teacherLayout.setBackgroundResource(R.color.white);
//        }
        if (!result) {
            ToastX.show(R.string.unfinish_form);
        }
        return result;
    }

    public void updateView() {
        titleEt.setText(formModel.getTitle());
        priceTv.setText(TextUtils.isEmpty(formModel.getPrice()) ? "" : getString(R.string.currency_symbols) + formModel.getPrice());
        courseTypeEt.setText(formModel.getCourseType());
        if (!ListUtil.isEmpty(formModel.getInterestList())) {
            interestTv.setText(InterestUtil.joinInterestListTitle("、", formModel.getInterestList()));
        } else {
            interestTv.setText("");
        }
        if (!TextUtils.isEmpty(formModel.getSuitablePeople())) {
            suitablePeopleEt.setText(formModel.getSuitablePeople());
        } else {
            suitablePeopleEt.setText("");
        }

        if (formModel.getPlatformDividend() != null) {
            platformDividendEt.setText(formModel.getPlatformDividend());
        } else {
            platformDividendEt.setText("");
        }

        if (!TextUtils.isEmpty(formModel.getLearnTarget())) {
            learnTargetEt.setText(formModel.getLearnTarget());
        } else {
            learnTargetEt.setText("");
        }
        if (!TextUtils.isEmpty(formModel.getTeacher())) {
            teacherEt.setText(formModel.getTeacher());
        } else {
            teacherEt.setText("");
        }

        courseIntroductionTv.setText(formModel.getCourseIntroduction());
        splitVideoTv.setText(String.format(getString(R.string.have_selected_videos_num), formModel.getPublishLearnVideoItemList().size()));

        if (TextUtils.isEmpty(formModel.getCoverUrl())) {
            coverIv.setVisibility(View.INVISIBLE);
        } else {
            coverIv.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(formModel.getCoverUrl())
                    .apply(RequestOptions.placeholderOf(android.R.color.white))
                    .into(coverIv);
        }
        guaranteeTv.setText(GuaranteeUtil.joinGuaranteeTitle(formModel.getSelectGuaranteeItemList(), ","));
    }

    @Override
    protected void onPause() {
        containterLayout.requestFocus();
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_EDIT_SPLIT_VIDEO:
                if (resultCode == RESULT_OK) {
                    PublishLearnVideoFormModel tempFormModel = data.getParcelableExtra(PublishLearnVideoSplitPage.EXTRA_KEY_FORM_MODEL);
                    formModel = tempFormModel == null ? formModel : tempFormModel;
                }
                break;

            case REQUEST_CODE_INPUT_TITLE: {
                if (resultCode == RESULT_OK) {
                    formModel.setTitle(data.getStringExtra(SingleLineInputPage.EXTRA_KEY_INPUT_STRING));
                    {
                        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                            HashMap<String, String> attrs = new HashMap<>();
                            attrs.put("modify", "0");
                            trackEvent.sendEvent(this, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT_LABEL, attrs, true);
                        }
                    }
                }
                break;
            }
            case REQUEST_CODE_SELECT_COVER: {
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        formModel.setCoverUrl(LocalMediaUtil.getFirstItemCutPath(selectList));
                    }
                    mediaSource = TrackUtil.detectMediaSource(formModel.getCoverUrl());
                    {
                        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                            HashMap<String, String> attrs = new HashMap<>();
                            attrs.put("modify", "1");
                            trackEvent.sendEvent(this, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT_LABEL, attrs, true);
                        }
                    }
                }
                break;
            }
            case REQUEST_CODE_SELECT_PRICE: {
                if (resultCode == RESULT_OK) {
                    PriceItem priceItem = data.getParcelableExtra(SelectPricePage.EXTRA_KEY_SELECT_PRICE_DATA);
                    formModel.setPrice(priceItem.getPriceStr());
                    formModel.setPriceId(priceItem.getPriceId());
                    {
                        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                            HashMap<String, String> attrs = new HashMap<>();
                            attrs.put("modify", "2");
                            trackEvent.sendEvent(this, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT_LABEL, attrs, true);
                        }
                    }
                }
                break;
            }
            case REQUEST_CODE_SELECT_INTEREST: {
                if (resultCode == RESULT_OK) {
                    List<Interest> interestList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INTEREST_DATA);
                    List<Interest> industryList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INDUSTRY_DATA);
                    formModel.setInterestList(interestList);
                    formModel.setIndustryList(industryList);
                }
                break;
            }

            case REQUEST_CODE_INPUT_COURSE_INTRODUCTION: {
                if (resultCode == RESULT_OK) {
                    formModel.setCourseIntroduction(data.getStringExtra(InputIntrodutionPage.EXTRA_KEY_INPUT_STRING));
                    {
                        if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                            HashMap<String, String> attrs = new HashMap<>();
                            attrs.put("modify", "9");
                            trackEvent.sendEvent(this, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT_LABEL, attrs, true);
                        }
                    }
                }
                break;
            }
            case REQUEST_CODE_SELECT_GUARANTEE: {
                if (resultCode == RESULT_OK) {
                    {
                        Map<String, String> attrs = new HashMap<>();
                        switch (mediaSource) {
                            case TrackUtil.MEDIA_SOURCE_ALBUM:
                                attrs.put("cover_type", "3");
                                break;
                            case TrackUtil.MEDIA_SOURCE_CAMERA_SHOT:
                                attrs.put("cover_type", "1");
                                break;
                            case TrackUtil.MEDIA_SOURCE_DEFAULT:
                                attrs.put("cover_type", "0");
                                break;
                            case TrackUtil.MEDIA_SOURCE_SUB_VIDEO_COVER:
                                attrs.put("cover_type", "2");
                                break;
                        }
                        trackEvent.sendEvent(PublishLearnVideoFormPage.this, TrackEvent.SELECT_LEARN_VIDEO_COVER_TYPE, TrackEvent.SELECT_LEARN_VIDEO_COVER_TYPE_LABEL, attrs);
                    }
                    List<GuaranteeItem> selectedList = data.getParcelableArrayListExtra(GuaranteePage.EXTRA_KEY_GUARANTEE_DATA);
                    List<GuaranteeItem> guaranteeItemList = new LinkedList<>();
                    if (!ListUtil.isEmpty(selectedList)) {
                        guaranteeItemList.addAll(selectedList);
                    }
                    formModel.setSelectGuaranteeItemList(guaranteeItemList);
                    break;
                }

            }


            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
        updateView();
    }

    @OnClick({R.id.guaranteeExplainBtn, R.id.guaranteeLayout, R.id.platformDividendExplainBtn, R.id.titleBackBtn, R.id.titleLayout, R.id.coverLayout, R.id.priceLayout, R.id.interestLayout, R.id.courseIntroductionLayout, R.id.splitVideoLayout, R.id.saveBtn, R.id.submitBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.guaranteeExplainBtn:
                CommonTipDialog.newInstance(StringUtils.getString(R.string.guarantee_description))
                        .show(getSupportFragmentManager(), "");
                break;
            case R.id.platformDividendExplainBtn:
                CommonTipDialog.newInstance(StringUtils.getString(R.string.platform_dividend_description))
                        .show(getSupportFragmentManager(), "");
                break;

            case R.id.titleBackBtn:
                finish();
                containterLayout.requestFocus();
                break;
            case R.id.coverLayout: {
                containterLayout.requestFocus();
                List<LocalMedia> localMediaList = new LinkedList<>();
                List<PublishLearnVideoItem> publishLearnVideoItemList = formModel.getPublishLearnVideoItemList();
                for (PublishLearnVideoItem publishLearnVideoItem : publishLearnVideoItemList) {
                    if (publishLearnVideoItem.isPreUpload()) continue;
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPictureType("");
                    localMedia.setMimeType(PictureConfig.TYPE_IMAGE);
                    localMedia.setPath(publishLearnVideoItem.getCoverUrl());
                    localMediaList.add(localMedia);
                }
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .previewImage(false)
                        .isCamera(true)
                        .compress(false)
                        .enableCrop(true)
                        .withAspectRatio(16, 9)
                        .isZoomAnim(false)
                        .previewEggs(false)
                        .selectionMode(PictureConfig.SINGLE)
                        .extraMedias(localMediaList)
                        .forResult(REQUEST_CODE_SELECT_COVER);
                break;
            }
            case R.id.priceLayout: {
                containterLayout.requestFocus();
                PriceItem priceItem = PriceItem.newBuilder().build();
                try {
                    priceItem.setPriceId(formModel.getPriceId());
                    priceItem.setPriceStr(formModel.getPrice());
                    priceItem.setPriceValue(Double.parseDouble(formModel.getPrice()));
                } catch (Exception e) {
                    priceItem = null;
                }
                ARouter.getInstance()
                        .build(ARouterConfig.SelectPricePage)
                        .withParcelable("selectedPrice", priceItem)
                        .navigation(this, REQUEST_CODE_SELECT_PRICE);
                break;
            }

            case R.id.interestLayout: {
                containterLayout.requestFocus();
                ARouter.getInstance()
                        .build(ARouterConfig.SelectPublishInterestPage)
                        .withObject("selectedInterestList", formModel.getInterestList())
                        .withObject("publishIndustryList", formModel.getIndustryList())
                        .navigation(this, REQUEST_CODE_SELECT_INTEREST);
                break;
            }

            case R.id.courseIntroductionLayout: {
                containterLayout.requestFocus();
                ARouter.getInstance()
                        .build(ARouterConfig.InputIntroductionPage)
                        .withString("text", formModel.getCourseIntroduction())
                        .navigation(this, REQUEST_CODE_INPUT_COURSE_INTRODUCTION);
                break;
            }
            case R.id.splitVideoLayout: {
                containterLayout.requestFocus();
                trackEvent.sendEvent(this, TrackEvent.LEARN_VIDEO_MODIFY_SPLIT_VIDEO, TrackEvent.LEARN_VIDEO_MODIFY_SPLIT_VIDEO_LABEL);
                {
                    if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                        HashMap<String, String> attrs = new HashMap<>();
                        attrs.put("modify", "10");
                        trackEvent.sendEvent(this, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT, TrackEvent.LEARN_VIDEO_MOD_COL_TYPE_EDIT_LABEL, attrs, true);
                    }
                }
                ARouter.getInstance()
                        .build(ARouterConfig.PublishLearnVideoSplitPage)
                        .withParcelable("formModel", formModel)
                        .navigation(this, REQUEST_CODE_EDIT_SPLIT_VIDEO);
                break;
            }
            case R.id.guaranteeLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.GuaranteePage)
                        .withObject("preSelectArray", formModel.getSelectGuaranteeItemList())
                        .navigation(this, REQUEST_CODE_SELECT_GUARANTEE);
                break;
            case R.id.saveBtn: {
                containterLayout.requestFocus();
                if (!checkFormValidate()) {
                    return;
                }
                if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_COPY) {
                    doPublish(PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE);
                } else if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                    doPublish(PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE);
                } else {
                    doPublish(PublishUtil.PUBLISH_OPERATION_TYPE_SAVE);
                }
                break;
            }

            case R.id.submitBtn: {
                containterLayout.requestFocus();
                if (!checkFormValidate()) {
                    return;
                }
                if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_COPY) {
                    doPublish(PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW);
                } else if (formModel.getOperationType() == PublishUtil.OPERATION_TYPE_EDIT) {
                    doPublish(PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW);
                } else {
                    doPublish(PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW);
                }


                break;
            }
        }
    }

    protected void executePublish(final int publishOperationType) {
        if (!RxNetTool.isWifi(this) && ConfigUltis.isEnableGprsNotification()) {
            GprsNotificationDialogUtil.createPublishBuilder(this)
                    .setPositiveButton(R.string.confirm_upload, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new PublishLearnVideoTask().execute(publishOperationType, formModel);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .create()
                    .show();
        } else {
            new PublishLearnVideoTask().execute(publishOperationType, formModel);
        }
    }

    protected void doPublish(final int publishOperationType) {
        new CheckSensitiveWordTask(publishOperationType, formModel).execute();
    }

    public class CheckSensitiveWordTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        PublishLearnVideoFormModel formModel;
        int publishOperationType;

        public CheckSensitiveWordTask(int publishOperationType, PublishLearnVideoFormModel formModel) {
            this.formModel = formModel;
            this.publishOperationType = publishOperationType;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishLearnVideoFormPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().checkSensitiveWord(PublishUtil.convertLearnVideoFormModelToMoment(formModel)).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o == null) {
                executePublish(publishOperationType);
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            }
        }
    }

    @Override
    public void finish() {
        Intent data = new Intent();
        data.putExtra(EXTRA_KEY_FORM_MODEL, formModel);
        setResult(RESULT_CANCELED, data);
        super.finish();
    }


    public class PublishLearnVideoTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        LearnVideoModel learnVideoModel;
        int publishOperationType;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishLearnVideoFormPage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                publishOperationType = (Integer) objects[0];
                PublishLearnVideoFormModel formModel = (PublishLearnVideoFormModel) objects[1];
                learnVideoModel = PublishUtil.publishLearnVideo(publishOperationType, formModel);
                {
                    Map<String, String> attrs = new HashMap<>();
                    switch (mediaSource) {
                        case TrackUtil.MEDIA_SOURCE_ALBUM:
                            attrs.put("cover_type", "3");
                            break;
                        case TrackUtil.MEDIA_SOURCE_CAMERA_SHOT:
                            attrs.put("cover_type", "1");
                            break;
                        case TrackUtil.MEDIA_SOURCE_DEFAULT:
                            attrs.put("cover_type", "0");
                            break;
                        case TrackUtil.MEDIA_SOURCE_SUB_VIDEO_COVER:
                            attrs.put("cover_type", "2");
                            break;
                    }
                    trackEvent.sendEvent(PublishLearnVideoFormPage.this, TrackEvent.SELECT_LEARN_VIDEO_COVER_TYPE, TrackEvent.SELECT_LEARN_VIDEO_COVER_TYPE_LABEL, attrs);
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                PublishLearnVideoFormPage.super.finish();
                switch (publishOperationType) {
                    case PublishUtil.PUBLISH_OPERATION_TYPE_SAVE:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SAVE:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SAVE:
                        ToastX.show(R.string.saving_learn_video);
                        break;

                    case PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW:
                    case PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW:
                        ToastX.show(R.string.publishing_learn_video);
                        break;
                }
                PublishUtil.jumpToMMPage(PublishLearnVideoFormPage.this);
            }
        }
    }

    public class MaybeRequestDivide extends SafeAsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        boolean shouldRequest;
        PublishLearnVideoFormModel model;

        public MaybeRequestDivide(Activity activity, PublishLearnVideoFormModel model) {
            super(activity);
            this.model = model;
            divide = DivideUtil.getLearnVideoDivide();
            shouldRequest = divide == null;
            if (shouldRequest) {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(activity)
                        .message(R.string.loading)
                        .build();
            } else {
                loadingDialog = null;
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (loadingDialog != null) {
                loadingDialog.showLoading();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
            if (TextUtils.isEmpty(model.getPlatformDividend())) {
                model.setPlatformDividend(StringUtils.platformDividendFormat(divide.getDefaultValue() * 100));
            }
            updateView();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            if (!shouldRequest) {
                return null;
            }
            try {
                Response<ResponseBody> response = ApiManager.getService().getLearnVideoDivide().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                JSONArray jsonArray = JSON.parseArray(json);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                JSONObject data = JSON.parseObject(jsonObject.getString("data"));
                double max = data.getDouble("max");
                double min = data.getDouble("min");
                double defaultValue = data.getDouble("default");
                divide = Divide.newBuilder()
                        .defaultValue(defaultValue)
                        .max(max)
                        .min(min)
                        .timestamp(System.currentTimeMillis())
                        .build();
                DivideUtil.putLearnVideoDivide(divide);
            } catch (Exception e) {
                divide = Divide.newBuilder()
                        .defaultValue(0.5)
                        .max(1)
                        .min(0.4)
                        .timestamp(0)
                        .build();
            }
            return null;
        }
    }

}
